#include "FileTransport.h"

#include <muduo/base/Logging.h>
#include <muduo/net/EventLoop.h>

#include <boost/bind.hpp>

using namespace muduo;
using namespace muduo::net;

FileTransport::FileTransport(EventLoop* loop,
		const InetAddress& listenaddr)
	:server_(loop, listenaddr, "FileTransport")
{
	server_.setConnectionCallback(
			boost::bind(&FileTransport::onConnection,
				this, _1));
	server_.setMessageCallback(
			boost::bind(&FileTransport::onMessage,
				this,_1, _2, _3));
	server_.setWriteCompleteCallback(
			boost::bind(
			&FileTransport::onWriteCompleted,
			this, _1));
}

void FileTransport::start()
{
	server_.start();
}

void FileTransport::onConnection(const TcpConnectionPtr& conn)
{
	LOG_INFO<<"FileTransport - "<< conn->peerAddress().toIpPort()<<
		" -> "<<conn->localAddress().toIpPort() <<" is "
		<<(conn->connected()?"UP":"DOWN");
	if(conn->connected())
	{
		conn->send("YOU HAVE CONNECTED TO SERVER SUCCESSFULLY\n");
		//conn->shutdown();
	}
}

void FileTransport::onMessage(const TcpConnectionPtr& conn,
		Buffer* buf,
		Timestamp time)
{
	string msg(buf->retrieveAllAsString());
	LOG_INFO<<"["<<time.toString()<<"]"<<
		conn->name() << " got msg from: "<<
		conn->peerAddress().toIpPort() << "-" <<
		msg;
}


void FileTransport::onWriteCompleted(
	const muduo::net::TcpConnectionPtr& conn)
{
	LOG_INFO<<conn->name()<<" write completed!";
}
